const Router = require('koa-router')
const mysql = require('../util/mysql/mysql')
const md5 = require('md5-node')
const { SUCCESS, USER_ACCOUNT_EXIST } = require('../util/respone/index')

let role = new Router()

// 添加用户
role.post('/add_user', async (ctx, next) => {
  // 用户post过来的数据
  let postParams = ctx.request.body;
  // md5加密 passHash
  let passHash = md5(postParams.username + postParams.password)

  // -------数据库操作------
  let addSql = 'INSERT INTO user(userName,passHash,auth) VALUES(?,?,?)'
  let addSqlParams = [postParams.username, passHash, postParams.auth]
  await mysql.add(addSql, addSqlParams)
    .then(async res => {
      await SUCCESS(ctx,{},"创建角色成功")
    })
    .catch(async err => {
      if (err.errno === 1062) {
        await USER_ACCOUNT_EXIST(ctx)
      }
  })
})

// 删除用户
role.delete('/delete_user', async (ctx, next) => {
  let postParams = ctx.request.body
  
  // -----数据库操作-------
  let delSql = `DELETE FROM user WHERE userName = "${postParams.username}"`
  await mysql.delete(delSql)
    .then(async res => {
      await SUCCESS(ctx,{},"删除用户成功")
    })
    .catch(async err => { 
    console.log(err)
  })
})

// 修改用户信息
role.put('/put_user', async (ctx, next) => {
  let postParams = ctx.request.body
  let passHash = md5(postParams.username + postParams.password)

  // -----数据库操作-------
  let updateSql = "UPDATE user SET userName = ?, passHash = ?, auth = ? WHERE id = ?"
  let updateSqlParams = [postParams.username, passHash, postParams.auth, postParams.id]
  
  await mysql.update(updateSql, updateSqlParams)
    .then(async res => {
    await SUCCESS(ctx,{},"修改用户信息成功")
    })
    .catch(async err => {
    console.log(err)
  })
})

module.exports = { role }